package zhangyu.world.voltaic.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import zhangyu.world.voltaic.config.Config;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class AliyunOSSUtil {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);
    private Class<? extends AliyunOSSUtil> aClass=this.getClass();

//type==1  图片  ==2 视频
    public static String upload(int type,File file){
        logger.info("=========>OSS文件上传开始："+file.getName());
        String endpoint= Config.aliOssEndpoint;
        String accessKeyId=Config.aliKeyid;
        String accessKeySecret=Config.aliKeysecret;
        String bucketName=Config.aliOssBucketname;
        String picHost=Config.aliOssPicHost;
        String movieHost=Config.aliOssMovieHost;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        if(null == file){
            return null;
        }

        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        try {
            //容器不存在，就创建
            if(! ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            String name = file.getName();
            String suffix = file.getName().substring(name.lastIndexOf(".") + 1);
            //创建文件路径
            String fileUrl ="";
            if(type==1){
                fileUrl=picHost+"/"+(dateStr + "/" + UUID.randomUUID().toString().replace("-","")+"."+suffix);
            }else{
                fileUrl=movieHost+"/"+(dateStr + "/" + UUID.randomUUID().toString().replace("-","")+"."+suffix);
            }

            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //设置权限 这里是公开读
            ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
            if(null != result){
                AliyunOSSUtil.deleteFile(file.getName());
                logger.info("==========>OSS文件上传成功,OSS地址："+fileUrl);
                return fileUrl;
            }
        }catch (OSSException oe){
            logger.error(oe.getMessage());
        }catch (ClientException ce){
            logger.error(ce.getMessage());
        }finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }




    public static   String deleteFile(String fileName){
        try {
//            获取项目路径
            File directory=new File("");
            String canonicalPath = directory.getCanonicalPath();
            System.out.println(canonicalPath);
            File file = new File(canonicalPath);
            File Array[] = file.listFiles();
            for (File f : Array) {
                if (f.isFile()) {// 如果是文件
                    if (f.getName().equals(fileName)) {
                        f.delete();
                        return "删除文件成功";
                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "删除文件失败,该文件不存在";
    }
}